package com.mask.common.file.service;

import com.mask.common.file.config.FileProperties;
import com.mask.common.file.service.FileService;
import com.mask.common.file.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
@ConditionalOnProperty(prefix = "mask.file", name = "storage-type", havingValue = "LOCAL", matchIfMissing = true)
public class LocalFileService implements FileService {
    @Autowired
    private FileProperties properties;

    @Override
    public String upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String extension = FileUtils.getExtension(originalFilename);
        String fileName = UUID.randomUUID().toString() + extension;
        
        String dateDir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String relativePath = dateDir + "/" + fileName;
        
        File targetFile = new File(properties.getLocal().getPath() + "/" + relativePath);
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdirs();
        }
        
        file.transferTo(targetFile);
        return properties.getLocal().getDomain() + "/" + relativePath;
    }

    @Override
    public void delete(String filePath) {
        String realPath = filePath.replace(properties.getLocal().getDomain(), 
                                         properties.getLocal().getPath());
        File file = new File(realPath);
        if (file.exists() && file.isFile()) {
            file.delete();
        }
    }

    @Override
    public void download(String filePath, HttpServletResponse response) throws IOException {
        String realPath = filePath.replace(properties.getLocal().getDomain(), 
                                         properties.getLocal().getPath());
        File file = new File(realPath);
        if (!file.exists()) {
            throw new FileNotFoundException("文件不存在");
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + 
                          URLEncoder.encode(file.getName(), "UTF-8"));
        
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            byte[] buffer = new byte[1024];
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        }
    }
}